const puppeteer = require('puppeteer');
const getM3u8Detail = async (getNumbers, url, callback) => {
    let obj = {}
    const browser = await puppeteer.launch({
        headless: true,
        slowMo: 50,
    });
    const page = await browser.newPage();

    // other actions...
    // 拦截网络请求
    await page.setRequestInterception(true);


    page.on('request', interceptedRequest => {
        interceptedRequest.continue();
    });

    page.on('response', async res => {
        if (res.url().endsWith('.m3u8')) {
            // console.log('has m3u8')
            let text = await res.text()
            let textArr = text.split('\n')
            // 这里要判断是否直接下载了真是的m3u8
            const hasTs = textArr.some(_item => _item.endsWith('.ts'))
            textArr = textArr.filter(item => item && item.trim())
            obj.m3u8 = textArr
            obj.m3u8Url = res.url()
            if (hasTs) obj.realM3u8Url = res.url()
        }
    });

    // 延长页面的等待时间
    await page.goto(url, { waitUntil: 'load', timeout: 180000 });

    // 不同的页面这里等待的class不一样
    await page.waitForSelector('#playlist1 ul.stui-content__playlist > li')

    // 获取电视剧的集数
    var styleNumbers = await page.$$('#playlist1 ul.stui-content__playlist > li');
    obj.nums = Object.keys(styleNumbers).length

    // 获取电视剧的title
    const movieTitle = await page.$eval('a.text-fff', el => el.innerHTML)

    obj.movieTitle = movieTitle
    await browser.close();
    // console.log('puppeteer obj:', obj)
    callback && callback(obj)
}
// getM3u8Detail(true, 'http://www.diezhan.me/dalu/xinsanguo/play-0-0.html')
module.exports = getM3u8Detail
